//
//  ViewController.m
//  HeadIndustry
//
//  Created by jun on 2017/8/24.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "ViewController.h"
#import "SGLNavigationViewController.h"
#import "JRegisterController.h" // 注册页面
#import "JFiendPswController.h" // 找回密码


#import "JMeViewController.h"
#import "JShopCarViewController.h"
#import "JStoreViewController.h"
#import "JBarberShopViewController.h"
#import "JBeautifulViewController.h"

#import <AFNetworking.h>
#import <WXApi.h>

//#import "JButton.h"

#define tabBarHeight [ViewController getTabBarHeight]
#define standOutHeight 12.0f // 中间突出部分的高度

#define topViewHeight  100
#define topViewY  80

#define textFieldWidth  250
#define textFieldHeight  45

@interface ViewController ()<WXApiDelegate>

@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UITextField *pswTextField;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setConfigBgView) name:@"wxlogin" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registMethod:) name:@"zhucelogin" object:nil];
    
    [SVProgressHUD setBackgroundColor:[UIColor blackColor]];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    
    [self setTopViewBgImg];
    
    [self setWXLoginBtn];
    
}

- (void)registMethod:(NSNotification *)noti {
    
//    if ([noti.object integerValue] == 1) {
//        [self setupAlertController:@"该微信已经已绑定手机号，请使用微信直接登录"];
//    }
//    else {
        JRegisterController *regist = [[JRegisterController alloc]init];
    regist.inputType = 0;
        [self presentViewController:regist animated:YES completion:nil];
//    }
    
    
}

- (void)setConfigBgView {
    [SVProgressHUD dismiss];
    [self configTabbarViewController];
}

- (void)setTopViewBgImg
{
    self.view.backgroundColor = kRGBColor(245, 245, 245);
    
    UIImageView *imgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"logo_icon"]];
    imgView.frame = CGRectMake(kWindowW/2.0 - topViewHeight/2.0 , topViewY, topViewHeight, topViewHeight);
    [self.view addSubview:imgView];
    
    UITextField *nameTextField = [[UITextField alloc]initWithFrame:CGRectMake(kWindowW/2.0 - textFieldWidth/2.0, imgView.bottom + 40, textFieldWidth, textFieldHeight)];
    nameTextField.placeholder = @"请输入手机号";
    nameTextField.keyboardType = UIKeyboardTypeNumberPad;
    nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    nameTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:nameTextField];
    _nameTextField = nameTextField;
    
    UITextField *pswTextField = [[UITextField alloc]initWithFrame:CGRectMake(nameTextField.left, nameTextField.bottom + 20, textFieldWidth, textFieldHeight)];
    pswTextField.placeholder = @"请输入密码";
    pswTextField.secureTextEntry = YES;
    
//    pswTextField.keyboardType = UIKeyboardTypeASCIICapable;
    pswTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    pswTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:pswTextField];
    _pswTextField = pswTextField;
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(pswTextField.left, pswTextField.bottom + 10, 75, 40);
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(registBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    registBtn.tag = 0;
    [self.view addSubview:registBtn];
    
    UIButton *findBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    findBtn.frame = CGRectMake(pswTextField.right - 75, pswTextField.bottom + 10, 75, 40);
    [findBtn setTitle:@"找回密码" forState:UIControlStateNormal];
    [findBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [findBtn addTarget:self action:@selector(registBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    findBtn.tag = 1;
    [self.view addSubview:findBtn];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(pswTextField.left, registBtn.bottom + 20, pswTextField.width, 40);
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.backgroundColor = [UIColor redColor];
    loginBtn.layer.cornerRadius = 5;
//    [loginBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(loginBtnClick22:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    _nameTextField.text = @"13798513961";
    _pswTextField.text = @"123456";
    
}

- (void)setWXLoginBtn
{
    
    YYLabel *titleLa1 = [YYLabel new];
    titleLa1.top = kWindowH - 60;
    titleLa1.left = 0;
    titleLa1.size = CGSizeMake(kWindowW, 20);
    titleLa1.text = @"登陆即代表您同意我们的服务和隐私政策";
    titleLa1.font = kFONT_TITLE(14);
    titleLa1.textColor = kRGBColor(150, 150, 150);
    titleLa1.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLa1];
    
    YYLabel *titleLa = [YYLabel new];
    titleLa.top = kWindowH - 60 - 20;
    titleLa.left = 0;
    titleLa.size = CGSizeMake(kWindowW, 20);
    titleLa.text = @"第三方登录";
    titleLa.font = kFONT_TITLE(18);
    titleLa.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLa];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(kWindowW/2.0 - 30, titleLa.top - 10 - 60, 60, 60);
    [btn setBackgroundImage:[UIImage imageNamed:@"weixin1"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];

}

#pragma mark - 设置弹出提示语
- (void)setupAlertController:(NSString *)title {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:actionConfirm];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)loginBtnClick:(UIButton *)btn
{
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = WXAuthStateLogin;
        [WXApi sendReq:req];
    }
    else {
        [self setupAlertController:@"请先安装微信客户端"];
    }
}

- (void)registBtnClick:(UIButton *)btn
{
    if (btn.tag == 0) {
        if ([WXApi isWXAppInstalled]) {
            SendAuthReq *req = [[SendAuthReq alloc] init];
            req.scope = @"snsapi_userinfo";
            req.state = WXAuthStateRegist;
            [WXApi sendReq:req];
        }
        else {
            [self setupAlertController:@"请先安装微信客户端"];
        }
    }
    else
    {
        JRegisterController *regist = [[JRegisterController alloc]init];
        regist.inputType = 1;
        [self presentViewController:regist animated:YES completion:nil];
    }
    
}

//- (void)findBtnClick:(UIButton *)btn
//{
//    NSLog(@"找回密码");
//    JFiendPswController *registVC = [[JFiendPswController alloc]init];
//    [self presentViewController:registVC animated:YES completion:nil];
//}

- (void)loginBtnClick22:(UIButton *)btn
{
//    NSLog(@"登陆");
    
    NSString *phone = _nameTextField.text;
    NSString *psw = _pswTextField.text;
    
    
    
    if (phone.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空"];
        return;
    }
    
    if (psw.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"密码不能为空"];
        return;
    }

    
    if (![self validateBandCard:phone regularString:REG_PHONENUM_STR]) {
        [SVProgressHUD showErrorWithStatus:@"手机号格式不正确"];
        return;
    }
    
    if (![self validateBandCard:psw regularString:REG_PswNum_STR]) {
        [SVProgressHUD showErrorWithStatus:@"请输入6-18位密码"];
        return;
    }
    [self.view endEditing:YES];
    
    NSDictionary *dic = @{
                          @"Tel":phone,
                          @"Pwd":psw,
                          };
    
    NSString *url = @"Customers/AppLogin";
    [JNetManager loginRequestURL:url
                       parperDic:dic
                         success:^(id response) {
                             if (response) {
                                 [self configTabbarViewController];
                             }
                         } failure:^(NSString *err) {
                             [SVProgressHUD showErrorWithStatus:err];
                         }];
    
}

- (void)configTabbarViewController
{
    //设置UINavigationBar的外观属性
//    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.435 green:0.427 blue:0.533 alpha:1.000]];
    
    SGLNavigationViewController *store_NV = [[SGLNavigationViewController alloc]initWithRootViewController:[[JStoreViewController alloc]init]];
    store_NV.navigationBar.hidden = YES;
    
    SGLNavigationViewController *barbershop_NV = [[SGLNavigationViewController alloc]initWithRootViewController:[[JBarberShopViewController alloc]init]];
    barbershop_NV.navigationBar.hidden = YES;
    
    SGLNavigationViewController *beautiful_NV = [[SGLNavigationViewController alloc]initWithRootViewController:[[JBeautifulViewController alloc]init]];
    beautiful_NV.navigationBar.hidden = YES;
    
    
    SGLNavigationViewController *shopCar_NV = [[SGLNavigationViewController alloc]initWithRootViewController:[[JShopCarViewController alloc]init]];
    shopCar_NV.navigationBar.hidden = YES;
    
    SGLNavigationViewController *me_NV = [[SGLNavigationViewController alloc]initWithRootViewController:[[JMeViewController alloc]init]];
    me_NV.navigationBar.hidden = YES;
    
    NSArray *views = @[store_NV, barbershop_NV, beautiful_NV,shopCar_NV, me_NV];
    
    
//    UITabBarController *tabbar = [[UITabBarController alloc]init];
    

    //  取消tabber的背景色
    [[UITabBar appearance] setShadowImage:[[UIImage alloc]init]];
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc]init]];
    //  初始化菜单栏
    UITabBarController *tabC = [[UITabBarController alloc]init];
    //改变tabBar的背景颜色
    [tabC.tabBar insertSubview:[self drawTabbarBgImageView] atIndex:0];
    tabC.tabBar.opaque = YES;

    tabC.viewControllers = views;
    tabC.selectedIndex = 0;
    NSArray *itemName = @[@"商城",@"理发店", @"美丽圈",@"购物车", @"我"];
    NSArray *defaultImage = @[@"main_index_n",  @"main_shop_n", @"main_head_n",  @"main_shopcar_n", @"main_mycenter_n"];
    NSArray *selectImage = @[@"main_index_h",  @"main_shop_h", @"main_head_h",  @"main_shopcar_h", @"main_mycenter_h"];
    for(int numb = 0 ; numb < itemName.count; numb ++)
    {
        UITabBarItem *tabBarItem = (UITabBarItem *)tabC.tabBar.items[numb];
        //  设置通知
        
        if (numb==2)
        {
            [tabBarItem setImageInsets:UIEdgeInsetsMake( - standOutHeight/2-8, 0, standOutHeight/2+8, 0)];
        }
        else
        {
        }
        tabBarItem.image = [[UIImage imageNamed:defaultImage[numb]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        tabBarItem.selectedImage = [[UIImage imageNamed:selectImage[numb]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [tabBarItem setTitle:itemName[numb]];

    }

    //改变选中的字体颜色
    [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],NSForegroundColorAttributeName,nil]forState:UIControlStateSelected];
    

    UIWindow *window = [[[UIApplication sharedApplication]delegate]window];
    window.rootViewController = tabC;
}

// 画背景的方法，返回 Tabbar的背景
- (UIImageView *)drawTabbarBgImageView
{
//    NSLog(@"tabBarHeight：  %f" , tabBarHeight);// 设备tabBar高度 一般49
    CGFloat radius = 30;// 圆半径
    CGFloat allFloat= (pow(radius, 2)-pow((radius-standOutHeight), 2));// standOutHeight 突出高度 12
    CGFloat ww = sqrtf(allFloat);
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -standOutHeight,kWindowW , tabBarHeight +standOutHeight)];// ScreenW设备的宽

    CGSize size = imageView.frame.size;
    CAShapeLayer *layer = [CAShapeLayer layer];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(size.width/2 - ww, standOutHeight)];


    CGFloat angleH = 0.5*((radius-standOutHeight)/radius);

    CGFloat startAngle = (1+angleH)*((float)M_PI); // 开始弧度
    CGFloat endAngle = (2-angleH)*((float)M_PI);//结束弧度
    // 开始画弧：CGPointMake：弧的圆心  radius：弧半径 startAngle：开始弧度 endAngle：介绍弧度 clockwise：YES为顺时针，No为逆时针
    [path addArcWithCenter:CGPointMake((size.width)/2, radius) radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    // 开始画弧以外的部分
    [path addLineToPoint:CGPointMake(size.width/2+ww, standOutHeight)];
    [path addLineToPoint:CGPointMake(size.width, standOutHeight)];
    [path addLineToPoint:CGPointMake(size.width,size.height)];
    [path addLineToPoint:CGPointMake(0,size.height)];
    [path addLineToPoint:CGPointMake(0,standOutHeight)];
    [path addLineToPoint:CGPointMake(size.width/2-ww, standOutHeight)];
    layer.path = path.CGPath;
    layer.fillColor = [UIColor whiteColor].CGColor;// 整个背景的颜色
    layer.strokeColor = [UIColor colorWithWhite:0.765 alpha:1.000].CGColor;//边框线条的颜色
    layer.lineWidth = 0.5;//边框线条的宽
    // 在要画背景的view上 addSublayer:
    [imageView.layer addSublayer:layer];
    return imageView;
}

///**  绑定各个控制器, 顺便设置属性 */
//- (void)setupChildController:(UIViewController *)vc imageName:(NSString *)imgName selectedImage:(NSString *)selectedImgName {
//    // 设置图片间距
//    vc.tabBarItem.imageInsets = UIEdgeInsetsMake(5, 0, -5, 0);
//    vc.tabBarItem.image = [UIImage imageNamed:imgName];
//    // 设置图片的不渲染
//    UIImage *image = [[UIImage imageNamed:selectedImgName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    vc.tabBarItem.selectedImage = image;
//    [self addChildViewController:vc];
//}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

+(CGFloat)getTabBarHeight
{
    // 获取tabBarHeight
    UITabBarController *tabBarController =[[UITabBarController alloc]init];
    return CGRectGetHeight(tabBarController.tabBar.bounds);
}


- (BOOL)validateBandCard:(NSString *)baneCard regularString:(NSString *)regularString
{
    BOOL flag;
    if (baneCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSPredicate *bandCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularString];
    return [bandCardPredicate evaluateWithObject:baneCard];
}

@end
